<template>
  <div class="message-content">
    <div ref="textRef" class="leading-relaxed break-words">
      <div class="markdown-body" v-html="text"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import MarkdownIt from "markdown-it";
import mila from "markdown-it-link-attributes";
import mdKatex from "@traptitech/markdown-it-katex";
import hljs from "highlight.js";

const props = defineProps({
  textInfo: {
    type: String,
    default: "",
  },
});

const textRef = ref(null);

// 创建 markdown-it 实例
const mdi = new MarkdownIt({
  html: true,
  linkify: true,
  highlight(code, language) {
    const validLang = hljs.getLanguage(language);
    const lang = validLang ? language : "";
    const highlightedCode = validLang
      ? hljs.highlight(code, { language: lang }).value
      : hljs.highlightAuto(code).value;

    return `<div class="code-block-wrapper">
              <div class="code-header">
                <div class="header-right">
                  ${lang ? `<span class="code-lang">${lang}</span>` : ""}
                  <button class="copy-button" title="复制代码">
                    <svg class="copy-icon" viewBox="0 0 16 16" width="14" height="14">
                      <path fill="currentColor" d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z"></path>
                      <path fill="currentColor" d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path>
                    </svg>
                    <span class="copy-success">已复制</span>
                  </button>
                </div>
              </div>
              <pre><code class="hljs ${lang}">${highlightedCode}</code></pre>
            </div>`;
  },
});

// 配置 markdown-it 插件
mdi.use(mila, { attrs: { target: "_blank", rel: "noopener" } });
mdi.use(mdKatex, {
  blockClass: "katexmath-block rounded-md p-[10px]",
  errorColor: " #cc0000",
});

// 计算处理后的文本
const text = computed(() => {
  const value = props.textInfo.replaceAll("*", "") || "";
  return mdi.render(value);
});

// 设置代码块复制功能
const setupCodeCopy = () => {
  const codeBlocks = textRef.value?.querySelectorAll(".code-block-wrapper");
  if (!codeBlocks) return;

  codeBlocks.forEach((wrapper) => {
    const copyButton = wrapper.querySelector(".copy-button");
    const codeElement = wrapper.querySelector("code");
    const tooltip = wrapper.querySelector(".copy-tooltip");

    if (!copyButton || !codeElement) return;

    copyButton.addEventListener("click", async () => {
      try {
        await navigator.clipboard.writeText(codeElement.textContent || "");
        copyButton.classList.add("copied");
        tooltip.style.display = "block";
        tooltip.style.opacity = "1";

        setTimeout(() => {
          copyButton.classList.remove("copied");
          tooltip.style.opacity = "0";
          setTimeout(() => {
            tooltip.style.display = "none";
          }, 200);
        }, 2000);
      } catch (err) {
        console.error("复制失败:", err);
      }
    });
  });
};

// 监听内容变化
watch(
  () => props.textInfo,
  () => {
    setTimeout(setupCodeCopy, 0);
  },
  { flush: "post" }
);

// 组件挂载时初始化
onMounted(() => {
  setTimeout(setupCodeCopy, 0);
});
</script>

<style lang="scss">
.message-content {
  .code-block-wrapper {
    position: relative;
    margin: 10px 0;
    border-radius: 6px;
    background: #f6f8fa;
    border: 1px solid #d0d7de;

    .code-header {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding: 4px 12px;
      background: #f6f8fa;
      border-bottom: 1px solid #d0d7de;
      border-radius: 6px 6px 0 0;
      height: 28px;

      .header-right {
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .code-lang {
        font-size: 12px;
        color: #57606a;
        text-transform: lowercase;
        font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, monospace;
      }

      .copy-button {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        padding: 2px 6px;
        font-size: 12px;
        color: #57606a;
        background: transparent;
        border: 1px solid #d0d7de;
        cursor: pointer;
        border-radius: 4px;
        transition: all 0.2s ease;

        &:hover {
          color: #24292f;
          background: #f3f4f6;
          border-color: #bbc0c4;
        }

        .copy-success {
          display: none;
          font-size: 12px;
        }

        &.copied {
          color: #1a7f37;
          border-color: #1a7f37;
          background: #f6f8fa;

          .copy-icon {
            display: none;
          }

          .copy-success {
            display: inline;
          }
        }
      }
    }

    pre {
      margin: 0;
      padding: 12px;
      overflow-x: auto;
      background: #f6f8fa;

      code {
        font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, monospace;
        font-size: 13px;
        line-height: 1.45;
        color: #24292f;
      }

      &::-webkit-scrollbar {
        height: 6px;
      }

      &::-webkit-scrollbar-track {
        background: transparent;
      }

      &::-webkit-scrollbar-thumb {
        background: #d0d7de;
        border-radius: 3px;

        &:hover {
          background: #bbc0c4;
        }
      }
    }
  }
}

// 针对不同角色的样式调整
.user .message-content .code-block-wrapper {
  background: rgba(246, 248, 250, 0.9);

  .code-header {
    background: rgba(246, 248, 250, 0.9);
  }
}

.assistant .message-content .code-block-wrapper {
  background: #f6f8fa;

  .code-header {
    background: #f6f8fa;
  }
}

// 代码高亮主题调整为浅色主题
.hljs {
  color: #24292f;
  background: transparent;

  .hljs-keyword {
    color: #cf222e;
  }
  .hljs-built_in {
    color: #8250df;
  }
  .hljs-type {
    color: #953800;
  }
  .hljs-literal {
    color: #0550ae;
  }
  .hljs-number {
    color: #0550ae;
  }
  .hljs-regexp {
    color: #116329;
  }
  .hljs-string {
    color: #0a3069;
  }
  .hljs-subst {
    color: #24292f;
  }
  .hljs-symbol {
    color: #0550ae;
  }
  .hljs-class {
    color: #953800;
  }
  .hljs-function {
    color: #8250df;
  }
  .hljs-title {
    color: #953800;
  }
  .hljs-params {
    color: #24292f;
  }
  .hljs-comment {
    color: #6e7781;
  }
  .hljs-doctag {
    color: #116329;
  }
  .hljs-meta {
    color: #116329;
  }
  .hljs-section {
    color: #0550ae;
  }
  .hljs-tag {
    color: #24292f;
  }
  .hljs-name {
    color: #116329;
  }
  .hljs-attr {
    color: #0550ae;
  }
  .hljs-attribute {
    color: #0550ae;
  }
  .hljs-variable {
    color: #953800;
  }
}
</style>